--[[    分享
]]
local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. 'ExternalFun')
local MultiPlatform = appdf.req(appdf.EXTERNAL_SRC .. "MultiPlatform")
local utils = appdf.req(appdf.EXTERNAL_SRC .. "Utils")
local ShareLayer = class("ShareLayer", function(scene)
	local newLayer = display.newLayer(cc.c4b(0, 0, 0, 180))
	return newLayer
end)

function ShareLayer:ctor(_scene)
	self._scene = _scene
	
	self:loadCSB()
	self:initUI()
end

function ShareLayer:loadCSB()
	local root = ExternalFun.loadCSB("popView/shareLayer.csb", self)
	root = root:getChildByName("bg2_1")
	ExternalFun.playOpenLayerAnimation( root )
	self.csbNode = root
	ExternalFun.FixScaleUI(self.csbNode,true)
	
	self.btn_close = root:getChildByName("btn_close")
	self.btn_sharewx = root:getChildByName("Button_1_0")
	self.btn_shareqq = root:getChildByName("Button_1")
	
	self.nodePos = root:getChildByName("Node_1")
	
	local btncallback = function(ref, type)
		if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect( )
			ref:setScale(1)
			self:onButtonClicked(ref:getTag(), ref)
			ref:setScale(1)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
		end
	end
	
	self.btn_close:addTouchEventListener(btncallback)
	self.btn_sharewx:addTouchEventListener(btncallback)
	self.btn_shareqq:addTouchEventListener(btncallback)
end

function ShareLayer:initUI()
	local cfg = self._scene:getApp()._serverConfig
	local qrcodeurl = cfg.qrcode
	local localqrurl = cc.UserDefault:getInstance():getStringForKey("qrcodeurl", "")
	
	local savePath = cc.FileUtils:getInstance():getWritablePath() .. "download/"

	local callback = function( ret )
		if ret == appdf.DOWN_COMPELETED then
			if  self.nodePos then
				local sp = display.newSprite(savePath.."qrcode.png")
				 local size = sp:getContentSize()
				sp:setScale(216/size.width)
				self.nodePos:addChild(sp)
				cc.UserDefault:getInstance():setStringForKey("qrcodeurl",qrcodeurl)
			end
			
		end
	end
	if localqrurl == qrcodeurl and cc.FileUtils:getInstance():isFileExist(savePath.."qrcode.png")  then
		callback(appdf.DOWN_COMPELETED)
		return
	end
	appdf.onHttpDownUrl(qrcodeurl.."?channelid="..appdf.channelId,"qrcode.png",savePath,callback )
end

function ShareLayer:onButtonClicked(tag, ref)
	
	if ref == self.btn_close then
		self:removeFromParent()
	elseif ref == self.btn_sharewx then
			--判断应用是否安装
		utils.checkAPPInstalled("wxpay","微信未安装，请安装后重试")
		cc.Application:getInstance():openURL("weixin://")
	elseif ref == self.btn_shareqq then
			--判断应用是否安装
		utils.checkAPPInstalled("qqpay","QQ未安装，请安装后重试")
		cc.Application:getInstance():openURL("mqq://im/chat?chat_type=wpa")
	end
end

return ShareLayer

